#define _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*> q;
        if (root != NULL) q.push(root);
        while (!q.empty())
        {
            int size = q.size();
            for (int i = 0; i < size; i++)
            {
                Node* top = q.front();
                q.pop();
                if (i < (size - 1)) top->next = q.front();

                if (top->left) q.push(top->left);
                if (top->right) q.push(top->right);
            }
        }
        return root;
    }
};